'''
阳光个人意外伤害保险
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from pyquery import PyQuery as pq
from urllib.parse import urlencode
from common.helper import Helper
from urllib.parse import quote


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "阳光个人意外伤害保险"
        self.header_url = "https://product.sinosig.com/quote_quote.action?id=1538&insuredBuyNum=1&agentId=&source=&fuwu=&processId=buy-process-9983df20-ae43-4be7-bb87-bc2d80a5baff&orderSource=product-center&platform=pc&statisticProductType=01&statisticProductId=1538"

    # 生成产品信息
    def genProductInfo(self):

        # 意外身故
        accident_die = ["1", "2", "5", "10"]
        # 意外伤害医疗
        accident_treatment = ["0", "0.1", "0.2", "0.5","1"]
        # 意外伤害住院津贴日给付额
        accident_hospital = ["0"]
        # 职业
        doc = pq(url=self.header_url)

        items = doc(".behaviorSelect option").items()

        professions = []

        for item in items:
            data = {

                "professionCode": item.val(),
                "profession": item.text()
            }

            professions.append(data)

        for v in product(accident_die, accident_treatment, accident_hospital, professions):
            professionCode = v[3]["professionCode"]
            profession = v[3]["profession"]
            accident_injured = v[0]


            # 只有基本保障为10w元才会有 意外伤害医疗 1w 和 意外伤害住院津贴日给付额 10w
            # 写入数据库
            # print( v[0], accident_injured,v[1],v[2],professionCode,profession)
            self.mysql.cursor.execute(

                domain[self.name]["insert_sql"].format( v[0], accident_injured,v[1],v[2],professionCode,profession))

            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format( v[0], accident_injured,v[1],v[2],professionCode,profession))
            print("%s写入数据库成功" % self.name)

    # 获取sessionKey
    def requestSession(self):

        data = {

            "id": "1538",
            "insuredBuyNum": "1",
            "agentId": "",
            "source": "",
            "fuwu": "",
            "processId": "buy-process-9983df20-ae43-4be7-bb87-bc2d80a5baff",
            "orderSource": "product-center",
            "platform": "pc",
            "statisticProductType": "01",
            "statisticProductId": "1538",
        }

        url = 'https://product.sinosig.com/quote_quote.action?' + urlencode(data)


        header = {

            "Host": "product.sinosig.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
            "Accept-Encoding": "gzip, deflate, br",
            "Cookie": "acw_tc=76b20ff015766351089982997e57cacd08c742ed86c510f12d600637200bed; uv_cookie_id=uv-55a7978e-1b73-4258-acb9-c56c91797d9d; Hm_lvt_4d53bad78fe552efc6949c1036b46777=1576635112,1576641395,1576646130; Hm_lvt_041c5d3a51ebccd1458089723c2158f6=1576635112,1576641395,1576646130; WT_FPC=id=2eac7017fc8e2791a911576635112284:lv=1576647766822:ss=1576646130762; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2216f16c69bc023-07fe63c5e9ea04-4c322f7c-2073600-16f16c69bc126f%22%2C%22%24device_id%22%3A%2216f16c69bc023-07fe63c5e9ea04-4c322f7c-2073600-16f16c69bc126f%22%2C%22props%22%3A%7B%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; sajssdk_2015_cross_new_user=1; _ga=GA1.3.2084578367.1576635113; _gid=GA1.3.908215945.1576635113; SESSION=e41f677d-e35d-4aa7-8c25-14afacb21a81; Hm_lpvt_4d53bad78fe552efc6949c1036b46777=1576647766; Hm_lpvt_041c5d3a51ebccd1458089723c2158f6=1576647766; _gat_UA-8947761-4=1",
            "Connection": "keep-alive",

        }

        r = requests.get( url = url ,headers= header )

        if r.status_code == 200:

            doc = pq(r.text)

            sessionKey = doc(".content #diyProductForm input").eq(1).val()

            print( sessionKey )

            return sessionKey

    # 执行爬虫
    def requestJson(self, dt=None):

        data = "agentId=&" \
               "sessionKey="+self.requestSession()+"&" \
               "pagePropertyObj.selectedPlanId=2262&" \
               "pagePropertyObj.renewal=false&" \
               "pagePropertyObj.renewalCalendarStartDate=&" \
               "pagePropertyObj.renewalCalendarEndDate=&" \
               "source=&" \
               "fuwu=&" \
               "sso=true&" \
               "processId=buy-process-9983df20-ae43-4be7-bb87-bc2d80a5baff&" \
               "orderSource=product-center&" \
               "platform=pc&" \
               "statisticProductType=01&" \
               "statisticProductId=1538&" \
               "verifycode=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.clauseId=1539&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.liabilityId=1700&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.amount="+dt["accident_die"]+"&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.liabilityId=1820&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.amount="+dt["accident_injured"]+"&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.clauseId=1542&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.liabilityId=1701&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.amount="+dt["accident_treatment"]+"&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.clauseId=1543&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.liabilityId=1702&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.three=1&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.amount=0&" \
               "pagePropertyObj.workType="+quote(dt["professionCode"])+"&" \
               "pagePropertyObj.occupationLevel="+dt["professionCode"].split("|")[0]+"&" \
               "pagePropertyObj.occupationCode="+dt["professionCode"].split("|")[1]+"&" \
               "pagePropertyObj.occupationName="+quote(dt["profession"])+"&" \
               "pagePropertyObj.insuStartDate=2019-12-24&" \
               "pagePropertyObj.insuPeriod=1&" \
               "pagePropertyObj.insuPeriodUnit=03&" \
               "pagePropertyObj.insuEndDate=2020-12-23"


        r = requests.post(domain[self.name]["url"],headers=domain[self.name]["header"],data=data)

        if r.status_code == 200 and "产品报价出错，请刷新页面！" not in json.dumps( r.json(),ensure_ascii=False):

            price = Helper.decimalParse( r.json()["pagePropertyObj"]["totalPremium"] )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )



        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


    def test(self):

        from copyheaders import headers_raw_to_dict
        import requests

        sessionKey = self.requestSession()

        header = {

            "Host": "product.sinosig.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0",
            "Accept": "application/json, text/javascript, */*",
            "Accept-Language": "h-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
            "Accept-Encoding": "gzip, deflate, br",
            "Referer": "https://product.sinosig.com/quote_quote.action?id=1538&insuredBuyNum=1&agentId=&source=&fuwu=&processId=buy-process-9983df20-ae43-4be7-bb87-bc2d80a5baff&orderSource=product-center&platform=pc&statisticProductType=01&statisticProductId=1538",
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "MLHttpRequest",
            "Content-Length": "2459",
            "Cookie": "acw_tc=76b20ff015766351089982997e57cacd08c742ed86c510f12d600637200bed; uv_cookie_id=uv-55a7978e-1b73-4258-acb9-c56c91797d9d; Hm_lvt_4d53bad78fe552efc6949c1036b46777=1576635112,1576641395,1576646130; Hm_lvt_041c5d3a51ebccd1458089723c2158f6=1576635112,1576641395,1576646130; WT_FPC=id=2eac7017fc8e2791a911576635112284:lv=1576646130762:ss=1576646130762; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2216f16c69bc023-07fe63c5e9ea04-4c322f7c-2073600-16f16c69bc126f%22%2C%22%24device_id%22%3A%2216f16c69bc023-07fe63c5e9ea04-4c322f7c-2073600-16f16c69bc126f%22%2C%22props%22%3A%7B%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; sajssdk_2015_cross_new_user=1; _ga=GA1.3.2084578367.1576635113; _gid=GA1.3.908215945.1576635113; SESSION=e41f677d-e35d-4aa7-8c25-14afacb21a81; Hm_lpvt_4d53bad78fe552efc6949c1036b46777=1576646130; Hm_lpvt_041c5d3a51ebccd1458089723c2158f6=1576646130; _gat_UA-8947761-4=1",
            "Connection": "keep-alive",

        }

        url = "https://product.sinosig.com/quote_ajaxQuote.action"

        data = "agentId=&" \
               "sessionKey=myInsurance79e2bfe6-73d5-40b3-8569-eea03bc587ce&" \
               "pagePropertyObj.selectedPlanId=2262&" \
               "pagePropertyObj.renewal=false&" \
               "pagePropertyObj.renewalCalendarStartDate=&" \
               "pagePropertyObj.renewalCalendarEndDate=&" \
               "source=&" \
               "fuwu=&" \
               "sso=true&" \
               "processId=buy-process-9983df20-ae43-4be7-bb87-bc2d80a5baff&" \
               "orderSource=product-center&" \
               "platform=pc&" \
               "statisticProductType=01&" \
               "statisticProductId=1538&" \
               "verifycode=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.clauseId=1539&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.liabilityId=1700&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B0%5D.amount=10&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.liabilityId=1820&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B0%5D.ecLiabilities%5B1%5D.amount=10&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.clauseId=1542&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.liabilityId=1701&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.three=&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.isSelected=true&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B1%5D.ecLiabilities%5B0%5D.amount=1&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.clauseId=1543&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.liabilityId=1702&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.three=1&" \
               "pagePropertyObj.pageProduct.ecInsurancplans%5B0%5D.ecClauses%5B2%5D.ecLiabilities%5B0%5D.amount=0&" \
               "pagePropertyObj.workType=1%7C1201003%7C%E5%AD%A6%E7%94%9F&" \
               "pagePropertyObj.occupationLevel=1&" \
               "pagePropertyObj.occupationCode=&" \
               "pagePropertyObj.occupationName=&" \
               "pagePropertyObj.insuStartDate=2019-12-24&" \
               "pagePropertyObj.insuPeriod=1&" \
               "pagePropertyObj.insuPeriodUnit=03&" \
               "pagePropertyObj.insuEndDate=2020-12-23"

        r = requests.post(url=url, headers=header, data=data)

        print(r.text)


if __name__ == '__main__':
    s = Spider()
    s.main()
